from django import forms
from django.utils.safestring import mark_safe


class HorizontalFilterWidget(forms.SelectMultiple):
    """
    一个自定义的 Widget，用于实现类似 Django Admin filter_horizontal 的效果。
    """
    template_name = 'widgets/horizontal_filter.html'

    def get_context(self, name, value, attrs):
        context = super().get_context(name, value, attrs)
        # `value` 是当前已选中的 ID 列表
        # 我们需要将选中和未选中的选项分开
        selected_ids = set(value or [])

        # 从 queryset 中获取所有选项
        all_options = self.choices

        # 分离选中和未选中的选项
        unselected = [{'id':obj[0],'name':obj[1]} for obj in all_options if obj[0] not in selected_ids]
        selected = [{'id':obj[0],'name':obj[1]} for obj in all_options if obj[0] in selected_ids]

        context['unselected_options'] = unselected
        context['selected_options'] = selected

        # 为隐藏的 select 字段生成 ID，用于表单提交
        context['hidden_select_id'] = f"id_{name}_hidden"

        return context